<template>
  <view class="container">
    <!-- 商品图片轮播 -->
    <swiper class="swiper" circular indicator-dots autoplay :interval="3000" :duration="500">
      <swiper-item v-for="(image, index) in productImages" :key="index">
        <image :src="image" mode="aspectFill" class="swiper-image" @click="previewImage(index)"></image>
      </swiper-item>
    </swiper>

    <!-- 商品信息 -->
    <view class="product-info">
      <view class="price-box">
        <text class="price">¥{{product.price}}</text>
        <text v-if="product.support_points" class="points">{{product.points_price}}积分</text>
      </view>
      <view class="title-box">
        <text class="title">{{product.name}}</text>
      </view>
      <view class="sales-box">
        <text class="sales">销量 {{product.sales}}</text>
        <text class="stock">库存 {{product.stock}}</text>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-options" v-if="product.support_points || product.support_mixed">
      <text class="section-title">支付方式</text>
      <view class="payment-list">
        <view
            class="payment-item"
            :class="{active: paymentType === 0}"
            @click="paymentType = 0"
        >
          <text>在线支付</text>
        </view>
        <view
            class="payment-item"
            :class="{active: paymentType === 1}"
            @click="paymentType = 1"
            v-if="product.support_points"
        >
          <text>积分支付</text>
        </view>
        <view
            class="payment-item"
            :class="{active: paymentType === 2}"
            @click="paymentType = 2"
            v-if="product.support_mixed"
        >
          <text>混合支付</text>
        </view>
      </view>
    </view>

    <!-- 商品详情 -->
    <view class="product-detail">
      <text class="section-title">商品详情</text>
      <u-parse :html="product.description"></u-parse>
    </view>

    <!-- 底部操作栏 -->
    <view class="footer">
      <view class="footer-left">
        <view class="icon-btn" @click="goToHome">
          <u-icon name="home" size="40" color="#666"></u-icon>
          <text>首页</text>
        </view>
        <view class="icon-btn" @click="goToCart">
          <u-icon name="shopping-cart" size="40" color="#666"></u-icon>
          <text>购物车</text>
          <view class="cart-badge" v-if="cartBadgeCount > 0">{{cartBadgeCount}}</view>
        </view>
      </view>
      <view class="footer-right">
        <button class="add-cart-btn" @click="showQuantityPopup('cart')">加入购物车</button>
        <button class="buy-btn" @click="showQuantityPopup('buy')">立即购买</button>
      </view>
    </view>

    <!-- 数量选择弹窗 -->
    <u-popup v-model="quantityPopupVisible" mode="bottom" @close="closeQuantityPopup">
      <view class="quantity-popup">
        <view class="popup-header">
          <image :src="product.thumbnail || '/static/images/default-product.png'" mode="aspectFill" class="popup-image"></image>
          <view class="popup-info">
            <text class="popup-price">¥{{product.price}}</text>
            <text class="popup-stock">库存: {{product.stock}}件</text>
          </view>
          <u-icon name="close" size="30" @click="closeQuantityPopup"></u-icon>
        </view>

        <view class="popup-content">
          <view class="quantity-selector">
            <text class="quantity-label">购买数量</text>
            <view class="quantity-control">
              <view class="quantity-btn minus" :class="{disabled: quantity <= 1}" @click="decreaseQuantity">-</view>
              <input type="number" class="quantity-input" v-model="quantity" />
              <view class="quantity-btn plus" :class="{disabled: quantity >= product.stock}" @click="increaseQuantity">+</view>
            </view>
          </view>
        </view>

        <view class="popup-footer">
          <button class="confirm-btn" @click="confirmAction">确定</button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      id: null, // 商品ID
      product: {}, // 商品信息
      productImages: [], // 商品图片数组
      loading: false, // 加载状态
      paymentType: 0, // 支付方式：0在线支付，1积分支付，2混合支付
      quantity: 1, // 购买数量
      quantityPopupVisible: false, // 数量选择弹窗可见性
      actionType: '', // 操作类型：cart加入购物车，buy立即购买
      cartBadgeCount: 0 // 购物车徽标数量
    }
  },
  onLoad(options) {
    // 获取商品ID
    if (options.id) {
      this.id = options.id;
      this.loadProductDetail();
    } else {
      uni.showToast({
        title: '商品ID不存在',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  onShow() {
    // 更新购物车徽标数量
    this.updateCartBadge();
  },
  methods: {
    // 加载商品详情
    async loadProductDetail() {
      if (!this.id) return;

      try {
        this.loading = true;

        // 发起请求
        const res = await this.$api.getOfficeProduct(this.id);

        // 处理响应数据
        this.product = res || {};

        // 处理商品图片
        if (this.product.images) {
          try {
            // 尝试解析JSON字符串
            this.productImages = this.product.images.split(',');
          } catch (e) {
            console.error('解析商品图片出错', e);
            this.productImages = [];
          }
        }

        // 如果没有图片，添加缩略图
        if (this.productImages.length === 0 && this.product.thumbnail) {
          this.productImages = [this.product.thumbnail];
        }
      } catch (error) {
        console.error('获取商品详情失败', error);
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 预览图片
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.productImages
      });
    },

    // 跳转到首页
    goToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },

    // 跳转到购物车
    goToCart() {
      uni.switchTab({
        url: '/pages/cart/cart'
      });
    },

    // 显示数量选择弹窗
    showQuantityPopup(type) {
      this.actionType = type;
      this.quantityPopupVisible = true;
    },

    // 关闭数量选择弹窗
    closeQuantityPopup() {
      this.quantityPopupVisible = false;
      this.quantity = 1;
      this.actionType = '';
    },

    // 减少数量
    decreaseQuantity() {
      if (this.quantity > 1) {
        this.quantity--;
      }
    },

    // 增加数量
    increaseQuantity() {
      if (this.quantity < this.product.stock) {
        this.quantity++;
      }
    },

    // 确认操作
    confirmAction() {
      if (this.actionType === 'cart') {
        this.addToCart();
      } else if (this.actionType === 'buy') {
        this.buyNow();
      }

      this.closeQuantityPopup();
    },

    // 添加到购物车
    addToCart() {
      // 检查库存
      if (this.product.stock <= 0) {
        uni.showToast({
          title: '商品库存不足',
          icon: 'none'
        });
        return;
      }

      // 检查数量
      if (this.quantity > this.product.stock) {
        uni.showToast({
          title: `库存仅剩${this.product.stock}件`,
          icon: 'none'
        });
        this.quantity = this.product.stock;
        return;
      }

      // 构建购物车商品对象
      const cartItem = {
        id: this.product.id,
        name: this.product.name,
        thumbnail: this.product.thumbnail,
        price: this.product.price,
        points_price: this.product.points_price,
        quantity: this.quantity,
        payment_type: this.paymentType,
        selected: true,
        stock: this.product.stock, // 保存库存信息用于后续校验
        productType: 'water' // 标记为桶装水产品
      };

      // 获取现有购物车
      let cartList = uni.getStorageSync('cartList') || [];

      // 检查商品是否已在购物车中
      const existingIndex = cartList.findIndex(item => 
        item.id === cartItem.id && 
        item.payment_type === cartItem.payment_type && 
        item.productType === 'water'
      );

      if (existingIndex > -1) {
        // 更新数量，并检查库存
        const newQuantity = cartList[existingIndex].quantity + cartItem.quantity;
        if (newQuantity > this.product.stock) {
          uni.showToast({
            title: `库存不足，最多可添加${this.product.stock - cartList[existingIndex].quantity}件`,
            icon: 'none'
          });
          return;
        }
        cartList[existingIndex].quantity = newQuantity;
        cartList[existingIndex].stock = this.product.stock; // 更新库存信息
      } else {
        // 添加新商品
        cartList.push(cartItem);
      }

      // 保存购物车
      uni.setStorageSync('cartList', cartList);

      // 更新购物车徽标
      this.updateCartBadge();

      // 提示成功
      uni.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
    },

    // 立即购买
    buyNow() {
      // 检查库存
      if (this.product.stock <= 0) {
        uni.showToast({
          title: '商品库存不足',
          icon: 'none'
        });
        return;
      }

      // 检查数量
      if (this.quantity > this.product.stock) {
        uni.showToast({
          title: `库存仅剩${this.product.stock}件`,
          icon: 'none'
        });
        this.quantity = this.product.stock;
        return;
      }

      // 构建订单商品对象
      const orderItem = {
        id: this.product.id,
        name: this.product.name,
        thumbnail: this.product.thumbnail,
        price: this.product.price,
        points_price: this.product.points_price,
        quantity: this.quantity,
        payment_type: this.paymentType,
        stock: this.product.stock,
        productType: 'water' // 标记为桶装水产品
      };

      // 构建订单预览数据
      const orderPreview = {
        products: [orderItem]
      };

      // 保存订单预览数据到本地存储
      uni.setStorageSync('orderItems', [orderItem]);

      // 跳转到订单确认页面
      uni.navigateTo({
        url: '/pages/waterShop/order/confirm'
      });
    },

    // 更新购物车徽标数量
    updateCartBadge() {
      const cartList = uni.getStorageSync('cartList') || [];
      // 只计算桶装水类型的商品数量
      this.cartBadgeCount = cartList.filter(item => item.productType === 'water').length;
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

.swiper {
  width: 100%;
  height: 750rpx;
}

.swiper-image {
  width: 100%;
  height: 100%;
}

.product-info {
  padding: 30rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
}

.price-box {
  display: flex;
  align-items: baseline;
}

.price {
  font-size: 40rpx;
  color: #ff5500;
  font-weight: bold;
}

.points {
  margin-left: 15rpx;
  font-size: 28rpx;
  color: #909399;
}

.title-box {
  margin-top: 20rpx;
}

.title {
  font-size: 32rpx;
  color: #333333;
  line-height: 1.5;
}

.sales-box {
  margin-top: 20rpx;
  display: flex;
}

.sales, .stock {
  font-size: 26rpx;
  color: #909399;
}

.stock {
  margin-left: 30rpx;
}

.payment-options {
  padding: 30rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  color: #333333;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}

.payment-list {
  display: flex;
}

.payment-item {
  padding: 15rpx 30rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  margin-right: 20rpx;
  font-size: 28rpx;
  color: #333333;
}

.payment-item.active {
  border-color: #2979ff;
  color: #2979ff;
  background-color: rgba(41, 121, 255, 0.05);
}

.product-detail {
  padding: 30rpx;
  background-color: #ffffff;
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #ffffff;
  display: flex;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 9;
}

.footer-left {
  display: flex;
  width: 35%;
}

.icon-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
}

.icon-btn text {
  font-size: 22rpx;
  color: #666666;
  margin-top: 5rpx;
}

.cart-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background-color: #ff5500;
  color: #ffffff;
  font-size: 20rpx;
  padding: 5rpx 10rpx;
  border-radius: 50%;
  z-index: 1;
}

.footer-right {
  display: flex;
  width: 65%;
}

.add-cart-btn, .buy-btn {
  flex: 1;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28rpx;
  border-radius: 0;
}

.add-cart-btn {
  background-color: #ff9500;
  color: #ffffff;
}

.buy-btn {
  background-color: #ff5500;
  color: #ffffff;
}

.quantity-popup {
  background-color: #ffffff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  padding-bottom: env(safe-area-inset-bottom);
}

.popup-header {
  display: flex;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.popup-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
}

.popup-info {
  flex: 1;
  padding: 0 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.popup-price {
  font-size: 36rpx;
  color: #ff5500;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.popup-stock {
  font-size: 26rpx;
  color: #909399;
}

.popup-content {
  padding: 30rpx;
}

.quantity-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quantity-label {
  font-size: 28rpx;
  color: #333333;
}

.quantity-control {
  display: flex;
  align-items: center;
}

.quantity-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 36rpx;
  background-color: #f5f5f5;
  color: #333333;
  border-radius: 8rpx;
  line-height: 1;
  position: relative;
}
.quantity-btn.disabled {
  color: #c0c4cc;
}

.quantity-input {
  width: 80rpx;
  height: 60rpx;
  text-align: center;
  margin: 0 10rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
}

.popup-footer {
  padding: 30rpx;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  background-color: #2979ff;
  color: #ffffff;
  font-size: 30rpx;
  border-radius: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
